<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;
use App\Models\Device;
use Workerman\Connection\TcpConnection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\EsserAlarmLog;

class GetEsserData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'get-esser-data {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 新建WebSocket协议
        $ws_worker = new Worker("tcp://0.0.0.0:4001");

        // 启动4个进程对外提供服务
        // $ws_worker->count = 4;
        //当浏览器连接的时候触发此函数

        $ws_worker->onConnect = function($connection){
            $connection->id = $connection->getRemoteIp();
        };
        // 当收到客户端发来的数据后返回给所有客户端
        $ws_worker->onMessage = function(TcpConnection $connection, $data)
        {
            $ip = $connection->id;
            
            $arr = explode('54',trim($data,' '));
            $insertdata['created_at'] = date('Y-m-d H:i:s',time());
            $insertdata['ip'] = $ip;
            $info = [];
            // $status[$ip]  = ['0c'=>['status'=>0,'time'=>time()],'44'=>['status'=>0,'time'=>time()],'c8'=>['status'=>0,'time'=>time()],'38'=>['status'=>0,'time'=>time()],
            // '28' => [['status'=>0,'time'=>time(),'str'=>712]],'04' => [['status'=>0,'time'=>time(),'str'=>712]]];
            // $ipinfo = json_decode(Redis::get($ip),1);
            // Log::info($arr);
            $lastkey = array_key_last($arr); //为空不存，
            $alarmarr = [];//总结此次报警
            foreach($arr as $key => $value) {
                if(empty($value)){
                    continue;
                }
                $insertdata['code'] = trim($value,' ');
                $framelist = explode(' ',trim($value,' '));
                // if($framelist[0] != '1c'){ //断续
                //     $framelist = array_merge($ipinfo['last'],$framelist);
                // }
                $errCode = $framelist[1];
                $f1 = isset($framelist[2])?intval($framelist[2]):'';
                $f2 = isset($framelist[3])?intval($framelist[3]):'';
                $f3 = isset($framelist[4])?intval($framelist[4]):'';
                
                if($errCode == 'c0'){//时间信息 
                    continue;
                }
                if($errCode == '0c'){//电源故障 报文只有 1c 0c 01 52 54 这5位
                    $alarmarr['0c'] = 1;
                }
                if($errCode == '44'){//开锁
                    $alarmarr['44'] = 1;
                }
                if($errCode == 'c8'){//回路故障
                    $alarmarr['c8'] = 1;
                }
                if($errCode == '28'){//火警
                    $z1 = ($f1 >> 2) & 0x3f;
                    $z2 = (($f2 >> 7) & 0x01) * 64 * 100 + (($f2 >> 2) & 0x03) *64;
                    $z3 = (($f3 >> 2) & 0x3f) * 100;
                    //区域
                    $zone = $z1+$z2+$z3;
                    $insertdata['zone'] = $zone;
                    $key = $zone;
                    if (count($framelist) > 6){
                        $f4 = intval($framelist[5]);
                        $dot = ($f4 >> 2); //点
                        $key = $zone.'-'.$dot;
                        $insertdata['dot'] = $dot;
                    }
                    $alarmarr['28'][$zone.'-'.$dot] = 1;
                }
                if($errCode == '04')//故障 
                {
                    $z1 = ($f1 >> 2) & 0x3f;
                    $z2 = (($f2 >> 7) & 0x01) * 64 * 100 + (($f2 >> 2) & 0x03) *64;
                    $z3 = (($f3 >> 2) & 0x3f) * 100;
                    //区域
                    $zone = $z1+$z2+$z3;
                    $insertdata['zone'] = $zone;
                    $key = $zone;
                    if (count($framelist) > 6)
                    {
                        $f4 = intval($framelist[5]);
                        $dot = ($f4 >> 2); //点
                        $key = $zone.'-'.$dot;
                        $insertdata['dot'] = $dot;
                    }
                    $alarmarr['04'][$zone.'-'.$dot] = 1;
                }
                if($errCode == '38'){//技术报警
                    $alarmarr['38'] = 1;
                    $key = $ip.'-38';
                    if(!isset($info['38'])){
                        $info['38'] = ['type'=>'38','time'=>date('Y-m-d H:i:s',time()),'zone'=>'','dot'=>''];
                    }
                }
                // 遍历当前进程所有的客户端连接，发送客户端的数据
                // foreach($ws_worker->connections as $connection)
                // {
                //     $connection->;send($data);
                // }
            };
            $redres = json_decode(Redis::get($ip),1);
            
            if(!empty($alarmarr)){
                $a[$ip] = $alarmarr;
                $redres = json_decode(Redis::get($ip),1);
                //0c 44 c8 38
                if(isset($alarmarr['0c'])){
                    if($redres['0c']['status']==0){
                        $redres['0c']['status'] = 1;
                        $redres['0c']['time'] = time();
                    }
                }else{
                    $redres['0c']['status'] = 0;
                    $redres['0c']['time'] = time();
                }
                if(isset($alarmarr['44'])){
                    if($redres['44']['status']==0){
                        $redres['44']['status'] = 1;
                        $redres['44']['time'] = time();
                    }
                }else{
                    $redres['44']['status'] = 0;
                    $redres['44']['time'] = time();
                }
                if(isset($alarmarr['c8'])){
                    if($redres['c8']['status']==0){
                        $redres['c8']['status'] = 1;
                        $redres['c8']['time'] = time();
                    }
                }else{
                    $redres['c8']['status'] = 0;
                    $redres['c8']['time'] = time();
                }
                if(isset($alarmarr['38'])){
                    if($redres['38']['status']==0){
                        $redres['38']['status'] = 1;
                        $redres['38']['time'] = time();
                    }
                }else{
                    $redres['38']['status'] = 0;
                    $redres['38']['time'] = time();
                }
                foreach($redres['28'] as $key => &$val){
                    if(isset($alarmarr['28'][$val['str']])){
                        if($val['status']==0){
                            $val['status'] = 1;
                            $val['time'] = time();
                        }
                    }else{
                        $val['status'] = 0;
                        $val['time'] = time();
                    }
                }
                foreach($redres['04'] as $key => &$val){
                    if(isset($alarmarr['04'][$val['str']])){
                        if($val['status']==0){
                            $val['status'] = 1;
                            $val['time'] = time();
                        }
                    }else{
                        $val['status'] = 0;
                        $val['time'] = time();
                    }
                }
                Log::info($redres);
                Redis::set($ip,json_encode($redres));
                $device = Device::where(['address'=>$ip])->get()->toArray();
                $json = file(public_path('/json/8.json'));
                $point = json_decode($json[0],1);
                foreach($point as $key => &$values){
                    $val = json_decode($values,1);
                    if(isset($alarmarr['04'][$val['cid']])){
                        $val['type'] = 3;
                    }
                    if(isset($alarmarr['28'][$val['cid']])){
                        $val['type'] = 3;
                    }
                    $values = json_encode($val);
                }
                $file = public_path('/json/8.json');
                file_put_contents($file, json_encode($point));
                
                
            }
        };
        Worker::runAll();
    }
}
